import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Workspace } from '../../entities/workspace.entity';
import { CreateWorkspaceDto } from './dto/create-workspace.dto';
import { UpdateWorkspaceDto } from './dto/update-workspace.dto';
import { WorkspaceStatus } from '../../types/enums';

@Injectable()
export class WorkspaceService {
  constructor(
    @InjectRepository(Workspace)
    private workspaceRepository: Repository<Workspace>,
  ) {}

  async create(createWorkspaceDto: CreateWorkspaceDto, userId: string): Promise<Workspace> {
    const workspace = this.workspaceRepository.create({
      ...createWorkspaceDto,
      createdById: userId,
      status: WorkspaceStatus.ACTIVE,
    });

    return this.workspaceRepository.save(workspace);
  }

  async findAll(): Promise<Workspace[]> {
    return this.workspaceRepository.find({
      where: { status: WorkspaceStatus.ACTIVE },
      relations: ['createdBy'],
    });
  }

  async findByUser(userId: string): Promise<Workspace[]> {
    return this.workspaceRepository.find({
      where: { createdById: userId, status: WorkspaceStatus.ACTIVE },
      relations: ['createdBy'],
    });
  }

  async findOne(id: string): Promise<Workspace> {
    const workspace = await this.workspaceRepository.findOne({
      where: { id, status: WorkspaceStatus.ACTIVE },
      relations: ['createdBy'],
    });

    if (!workspace) {
      throw new NotFoundException(`工作区不存在`);
    }

    return workspace;
  }

  async update(id: string, updateWorkspaceDto: UpdateWorkspaceDto): Promise<Workspace> {
    const workspace = await this.findOne(id);
    
    if (updateWorkspaceDto.name !== undefined) {
      workspace.name = updateWorkspaceDto.name;
    }
    
    if (updateWorkspaceDto.description !== undefined) {
      workspace.description = updateWorkspaceDto.description;
    }
    
    if (updateWorkspaceDto.status !== undefined) {
      workspace.status = updateWorkspaceDto.status;
    }
    
    return this.workspaceRepository.save(workspace);
  }

  async softDelete(id: string): Promise<void> {
    const workspace = await this.findOne(id);
    
    workspace.status = WorkspaceStatus.DELETED;
    
    await this.workspaceRepository.save(workspace);
  }

  async permanentDelete(id: string): Promise<void> {
    const workspace = await this.workspaceRepository.findOne({
      where: { id },
    });

    if (!workspace) {
      throw new NotFoundException(`工作区不存在`);
    }

    await this.workspaceRepository.remove(workspace);
  }
} 